#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#define MAXLINE 1024
/*添加消息返回的来源判断*/

int main(int argc, char *argv[]) {
    int sockfd, sport;
    struct sockaddr_in serv;
    char *serv_ip = 0;

    if(argc < 3) {
        printf("please checkout format\n");
        return -1;
    }
    serv_ip = argv[1];
    sport = atoi(argv[2]);

    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        return -1;
    }

    memset(&serv, 0, sizeof(struct sockaddr_in));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(sport);
    inet_pton(AF_INET, serv_ip, &serv.sin_addr);

    if(connect(sockfd, (struct sockaddr *)&serv, sizeof(serv)) < 0) {
        perror("connect");
        return -1;
    }

    int n;
    char sendline[MAXLINE], recvline[MAXLINE];

    while(fgets(sendline, MAXLINE, stdin) != NULL) {
        
        n = write(sockfd, sendline, strlen(sendline));
        
        if (n < 0) {
            perror("send");
            break;
        }
        
        n = read(sockfd, recvline, MAXLINE);
        if ( n < 0 ) {
            perror("recvfrom");
            break;
        }
        recvline[n] = '\0';
        fputs(recvline, stdout);
    }
    return 0;
}